import type { SearchSelectorConfig } from '../../../../module/page_enhancer/appearance/style_enhancement/platforms'
import type { GooglePageTypeResult } from './types'
import { getCurrentSearch, GOOGLE_HOSTNAME_HK } from '../../../../types/constants'
import { PageRoute } from '../../../abstract/page_route'
import { GOOGLE_SEARCH_PAGE_SELECTORS, GooglePageType } from './types'

export class GooglePage extends PageRoute {
  readonly name: string = 'GooglePage'
  private static instance: GooglePage
  get pageType(): GooglePageType | 'default' {
    return this.getCurrentPageMeta().type
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): GooglePage {
    if (!GooglePage.instance) {
      GooglePage.instance = new GooglePage()
    }
    return GooglePage.instance
  }

  /**
   * 获取结果选择器
   */
  getResultSelectors(pageType?: GooglePageType, includeHideElement: boolean = false): SearchSelectorConfig {
    return this.resultSelectors(
      {
        pageType: pageType || this.pageType,
        selectorConfig: GOOGLE_SEARCH_PAGE_SELECTORS,
        includeHideElement,
        supportedPages: [
          GooglePageType.All,
          GooglePageType.Video,
          GooglePageType.Web,
          GooglePageType.News,
          GooglePageType.Books,
        ],
      },
    )
  }

  /**
   * 获取当前页面类型
   */
  public getCurrentPageMeta(): GooglePageTypeResult {
    const url = this.getCurrentUrl()
    const hostname = new URL(url).hostname
    const path = new URL(url).pathname

    // 404 页面检测
    const notFoundResult = this.detectNotFoundPage()
    if (notFoundResult)
      return notFoundResult

    // 首页
    if (/^\/?$/.test(path)) {
      if (hostname === GOOGLE_HOSTNAME_HK) {
        return { type: GooglePageType.IndexHk }
      }
      else {
        return { type: GooglePageType.Index }
      }
    }

    // 基础页面检测
    const pageResult = this.detectPages(path)
    if (pageResult)
      return pageResult

    // 未定义页面
    return { type: GooglePageType.Undefined }
  }

  /**
   * 检测 404 页面
   */
  private detectNotFoundPage(): GooglePageTypeResult | null {
    const pageNotFoundRules = [
      /404.*Not Found/i, // 不区分大小写
    ]

    if (pageNotFoundRules.some(regex => regex.test(document.title))) {
      return { type: GooglePageType.NotFound }
    }

    return null
  }

  /**
   * 检测其他功能页面
   */
  private detectPages(basePath: string): GooglePageTypeResult | null {
    const pageDetectors: Array<[RegExp, (...args: any[]) => GooglePageTypeResult]> = [
      // 搜索
      [/^\/search\/?$/, () => {
        return this.detectSearchType()
      }],
      // 高级搜索
      [/^\/advanced_search\/?$/, () => {
        return { type: GooglePageType.Advanced }
      }],
    ]

    for (const [regex, handler] of pageDetectors) {
      const match = basePath.match(regex)
      if (match) {
        return handler(match)
      }
    }

    return null
  }

  /**
   * 检测搜索类型
   */
  private detectSearchType(): GooglePageTypeResult {
    const urlParams = new URLSearchParams(getCurrentSearch())
    const typeParam = urlParams.get('udm')
    const tbmParam = urlParams.get('tbm')

    if (!typeParam) {
      if (tbmParam === 'nws') {
        return { type: GooglePageType.News }
      }

      return { type: GooglePageType.All }
    }
    else if (typeParam === '7') {
      return { type: GooglePageType.Video }
    }
    else if (typeParam === '14') {
      return { type: GooglePageType.Web }
    }
    else if (typeParam === '36') {
      return { type: GooglePageType.Books }
    }
    else if (typeParam === '39') {
      return { type: GooglePageType.ShortVideo }
    }
    else {
      return { type: GooglePageType.Undefined }
    }
  }
}
